<template>
  <div class="flow-list-wrapper">
    <el-button @click="addNewFlow" v-show="formDefinition.processForm" :icon="Plus" type="primary">新建流程</el-button>
    <el-table style="min-height: 200px; margin-top: 10px" v-show="formDefinition.processForm" :data="flows" border
              @row-click="flowRowClick">
      <el-table-column prop="name" label="流程名称"/>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column prop="action" label="操作" width="200">
        <template #default="scope">
          <el-button link type="primary" @click.stop="edit(scope)">
            编辑
          </el-button>

          <el-button link type="warning" @click.stop="remove(scope)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="flow-list-footer">
      <el-button round style="margin-right: 10px" type="warning" icon="cancel">取消</el-button>
      <el-button round type="primary" style="margin-right: 10px" icon="save" @click="saveForm">保存单据</el-button>
    </div>
  </div>
</template>

<script>
import {DefaultFormDefinition} from '@/components/form/DefaultFormDefinition';
import {Plus} from '@element-plus/icons-vue';
import {guid, isEmpty, isNotEmpty, resolveSort} from '@/utils/CommonUtils';
import {postAction} from '@/request/BaseRequest';
import FormDesignParser from '@/components/form/FormFlowDesign/FormDesignParser';
import {ElMessageBox} from 'element-plus';
import moment from 'moment/moment';
import {DefaultFlowDefinition} from '@/components/flow/DefaultFlowDefinition';
import {markRaw} from 'vue';
import ViewActonHelper from '@/components/form/FromDesigner/ViewActonHelper';

export default {
  name: 'FormFlowDesign',
  components: {
    Plus
  },
  data() {
    return {
      loading: false,
      Plus: markRaw(Plus),
      formDefinition: DefaultFormDefinition,
      flows: []
    };
  },
  methods: {
    setData(formDefinition) {
      this.formDefinition = formDefinition;
      this.loadFlows();
    },
    loadFlows() {
      if (isNotEmpty(this.formDefinition.flows)) {
        this.flows = this.formDefinition.flows;
      } else {
        this.formDefinition.flows = this.flows = [];
      }
    },
    getFormDefinitionId() {
      if (this.formDefinition.id) return this.formDefinition.id;
      return '';
    },
    addFlow(flow) {
      this.flows.push(flow);
      this.formDefinition.flows = this.flows;
    },
    saveForm() {
      new ViewActonHelper(this.formDefinition);
      this.checkFormDefinition().then(() => {
        let formId = this.$route.query.formId;
        if (formId && formId !== '') {
          this.updateForm();
        } else {
          this.addForm();
        }
      });
    },
    checkFormDefinition() {
      return new Promise((success, err) => {

        if (!this.checkMainFields()) return;
        if (!this.checkSubForm()) return;
        success();
      });
    },
    checkMainFields() {
      let fields = this.formDefinition.fields;
      if (isEmpty(fields)) {
        this.$message.warning('主表至少需要建立一个字段');
        return false;
      }
      return true;
    },
    checkSubForm() {
      let subForms = this.formDefinition.subForms;
      for (let i = 0; i < subForms.length; i++) {
        let subForm = subForms[i];
        if (isEmpty(subForm.fields)) {
          this.$message.warning(`${subForm.showName} 至少需要一个字段`);
          return false;
        }
      }
      return true;
    },
    addForm() {
      this.formDefinition.id = null;
      this.formDefinition.appId = this.$route.query.appId;
      let data = this.resolveFormDefinition();
      this.loading = true;
      postAction("/plat/platForm/addForm", data).then(data => {
        if (data.success) {
          this.$message.success('保存成功!');
          this.$windowManager.close();
        } else {
          this.$notification.error({message: data.message, result: data.result, duration: 3});
        }
        this.loading = false;
      });
    },
    updateForm() {
      this.formDefinition.id = this.$route.query.formId;
      let data = this.resolveFormDefinition();
      this.loading = true;
      postAction("/plat/platForm/updateForm", data).then(data => {
        if (data.success) {
          this.$message.success('保存成功!');
          this.$windowManager.close();
        } else {
          this.$notification.error({message: data.message, result: data.result, duration: 3});
        }
        this.loading = false;
      });
    },
    resolveFormDefinition() {
      let list = this.flows, res = JSON.parse(JSON.stringify(this.formDefinition)), temp = [];
      let parser = new FormDesignParser(res);
      parser.parse();
      for (let i = 0; i < list.length; i++) {
        let item = {...list[i]};
        item.flowDefinition = JSON.stringify(item.flowDefinition);
        temp.push(item);
      }

      let fields = res.fields;
      for (let i = 0; i < fields.length; i++) {
        fields[i].sort = i + 1;
      }

      let subFroms = res.subForms;
      if (isNotEmpty(subFroms)) {
        for (let i = 0; i < subFroms.length; i++) {
          let subForm = subFroms[i];
          let fields = subForm.fields;
          resolveSort(fields);
        }
      }
      resolveSort(res.views);
      resolveSort(res.viewActions);
      list = res.viewActions;
      if (isEmpty(list)) list = [];
      list.forEach(viewAction => {
        resolveSort(viewAction.fieldActions);
        let fieldActions = viewAction.fieldActions;
        if (isEmpty(fieldActions)) viewAction.fieldActions = [];
        fieldActions.forEach(fieldAction => {
          resolveSort(fieldAction.actionFormulas);
        });
      });
      res.flows = temp;
      return res;
    },
    remove({row}) {
      ElMessageBox.confirm('确定删除?', 'Warning', {
        showClose: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      }).then(() => {
        let index = this.flows.findIndex(f => f.id === row.id);
        if (index !== -1) {
          this.flows.splice(index, 1);
        }
      }).catch(() => {
      });
    },
    flowRowClick(row) {
      this.edit({row});
    },
    edit({row}) {
      let url = `/form/flow/edit?fullScreen=1&formId=${this.getFormDefinitionId()}`;
      this.$windowManager.open(url, {
        title: '编辑流程',
        componentMounted: (w) => {
          w.setFormDefinition(this.formDefinition);
          w.setData(row);
        },
        updateFlow: (flow) => {
          this.updateFlow(flow);
        }
      });
    },
    handleSizeChange() {

    },
    handleCurrentChange() {

    },
    updateFlow(flow) {
      flow = JSON.parse(JSON.stringify(flow));
      let index = this.flows.findIndex(f => f.id === flow.id);
      if (index !== -1) {
        // this.flows[index] = flow;
        this.flows.splice(index, 1, flow);
      } else {
        this.flows.push(flow);
      }
    },
    createNewFlow: function () {
      let newFlowData = JSON.parse(JSON.stringify(DefaultFlowDefinition));
      newFlowData.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
      newFlowData.id = guid();
      newFlowData.pcViewId = this.formDefinition.views.find(v => v.main + '' === '1').id;
      newFlowData.pcViewActionId = this.formDefinition.viewActions.find(v => v.viewId === newFlowData.pcViewId && v.actionType === 'edit').id;

      newFlowData.mobileViewId = this.formDefinition.views.find(v => v.main + '' === '1').id;
      newFlowData.mobileViewActionId = this.formDefinition.viewActions.find(v => v.viewId === newFlowData.pcViewId && v.actionType === 'edit').id;
      newFlowData.processKey = guid();
      return newFlowData;
    },
    addNewFlow() {
      let url = `/form/flow/edit?fullScreen=1&formId=${this.getFormDefinitionId()}`;
      let key = guid();
      let newFlowData = this.createNewFlow();
      this.$windowManager.open(url, {
        title: '新建流程',
        componentMounted: (w) => {
          w.setData(newFlowData);
          w.setFormDefinition(this.formDefinition);
        },
        updateFlow: (flow) => {
          this.updateFlow(flow);
        }
      });
    },
  }
};
</script>

<style scoped>
.flow-list-footer {
  position: fixed;
  width: 100%;
  bottom: 0;
  z-index: 10;
  background: white;
  border-top: 1px solid #dcdfe6;
  text-align: right;
  padding: 5px 5px 5px 0;
  box-sizing: border-box;
  left: 0;
}

.flow-list-wrapper {
  overflow: auto;
  background: white;
  padding: 10px;
  height: calc(100vh - 59px);
  position: relative;
}

</style>
